package org.hepeng.fabric.contract.annotation;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author he peng
 * @date 2022/3/23
 */

@Retention(RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface TxFunction {

    Type type() default Type.SUBMIT;

    ArgType argType() default ArgType.JSON;

    String[] events() default {};

    enum Type {

        QUERY , SUBMIT
    }

    enum ArgType {



        PRIMITIVE {
            @Override
            public String[] convert(Object[] args) {
                String[] strArgs = new String[args.length];
                for (int i = 0; i < args.length ; i++) {
                    strArgs[0] = String.valueOf(args[0]);
                }
                return strArgs;
            }
        },

        JSON {
            @Override
            public String[] convert(Object[] args) {
                try {
                    return new String[] {OBJECT_MAPPER.writeValueAsString(args)};
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        };

        private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

        public abstract String[] convert(Object[] args);
    }
}
